package com.augrain.microframework.trace.wrapper;


import com.augrain.microframework.trace.context.TraceContext;
import com.augrain.microframework.trace.context.TraceContextSnapshot;

/**
 * Runnable包装类
 *
 * @author biaoy
 * @since 2024/12/28
 */
public class RunnableWrapper implements Runnable {

    private final Runnable task;

    private final TraceContextSnapshot snapshot;

    public RunnableWrapper(Runnable task, TraceContextSnapshot snapshot) {
        this.task = task;
        this.snapshot = snapshot;
    }

    public static RunnableWrapper of(Runnable runnable) {
        TraceContextSnapshot snapshot = TraceContext.snapshot();
        return new RunnableWrapper(runnable, snapshot);
    }

    @Override
    public void run() {
        if (task != null) {
            try {
                TraceContext.continued(snapshot);
                task.run();
            } finally {
                TraceContext.clear();
            }
        }
    }
}
